package com.bsj.travel.process.consumer.rocketmq;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSON;
import com.bsj.travel.config.rocketmq.constant.ConsumerGroupConstant;
import com.bsj.travel.config.rocketmq.producer.BaseMqPushUtil;
import com.bsj.travel.constant.BaseServerTopicConstants;
import com.bsj.travel.constant.MqttTopicPowerConstants;
import com.bsj.travel.def.common.DTO.mqtt.EventAct;
import com.bsj.travel.def.monitor.CloudLog;
import com.bsj.travel.process.handle.service.DefaultMessageService;
import com.bsj.travel.process.handle.service.bolt.BehaviorSaveService;
import com.bsj.travel.util.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author yinhao
 * @version 1.0
 * @description MQTT动作消息消费(集群消费)[消息上行][设备 -> 服务端]
 * @date 2023/11/10
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = BaseServerTopicConstants.TRAVEL_MQTT_MSG_PROCESS_TOPIC,
        consumerGroup = ConsumerGroupConstant.TRAVEL_MQTT_PROCESS_MSG_GROUP,
        selectorExpression = BaseServerTopicConstants.TRAVEL_MQTT_MSG_PROCESS_TAG
                + "||" + BaseServerTopicConstants.TRAVEL_MQTT_MSG_PROCESS_BEHAVIOR_TAG,
        messageModel = MessageModel.CLUSTERING)
public class MqttActionMessageRocketmqConsumer implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {

    @Autowired
    private DefaultMessageService defaultMessageService;

    @Autowired
    private BehaviorSaveService behaviorSaveService;

    @Autowired
    private BaseMqPushUtil baseMqPushUtil;

    @Async("travelAsync-mqttMsg-process")
    @Override
    public void onMessage(MessageExt ext) {
        String message = new String(ext.getBody());
        String tags = ext.getTags();
        log.info("TravelCloud-Mqtt物联网平台设备消息上行tag: {}, msg: {}", tags, message);
        try {
            EventAct event = JSON.parseObject(message, EventAct.class);
            CloudLog cloudLog = new CloudLog();
            cloudLog.setTs(event.getTimestamp());
            //生成随机30位字符串当做事务ID
            cloudLog.setTraceId(RandomUtil.randomString(30));
            cloudLog.setServeType(event.getServeType());
            cloudLog.setOperate(event.getOperate());
            if (event.getCode() == null) {
                //未知连接,不做记录
                return;
            }
            cloudLog.setContent(event.getEvent().getData() + "");
            cloudLog.setIdentify(event.getEvent().getClient());
            cloudLog.setCode(event.getCode());
            if (tags.equalsIgnoreCase(BaseServerTopicConstants.TRAVEL_MQTT_MSG_PROCESS_TAG)) {
                //主业务默认处理
                defaultMessageService.doPush(JSON.toJSONBytes(event.getEvent()));
            } else {
                //设备关于行为类数据处理,上线，离线，订阅，发布
                behaviorSaveService.doPush(ext.getBody());
            }
            //转交给日志处理器
            baseMqPushUtil.sendTopicBytes(BaseServerTopicConstants.TRAVEL_MQTT_LOG_MSG_RECORD_TOPIC,
                    BaseServerTopicConstants.TRAVEL_MQTT_LOG_MSG_RECORD_TAG, JSON.toJSONBytes(cloudLog));
            //消息订阅 TODO
        } catch (Exception e) {
            log.error("TravelCloud-Mqtt物联网平台数据消费-->消费失败，失败原因： {}", ExceptionUtil.getStackStr(e));
        }
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        // 设置消费者消息重试次数
        defaultMQPushConsumer.setMaxReconsumeTimes(3);
        //设置实例名称
        defaultMQPushConsumer.setInstanceName(MqttTopicPowerConstants.MQTT_PROCESS_ACTION_INSTANCE_NAME);
    }
}
